package com.hucsmn.stumansys.servlet.student;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.hucsmn.stumansys.entity.Admin;
import com.hucsmn.stumansys.entity.Student;
import com.hucsmn.stumansys.service.StudentService;
import com.hucsmn.stumansys.utils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Optional;

/**
 * 学生信息列举 API。
 *
 * 接收 HTTP 参数
 *      page        列表页数。可选，默认值 1，取值范围 >= 1。
 *      limit       每页数量。可选，默认值 10，取值范围 >= 1。
 *      contains    学生姓名需要包含的字符串。可选。
 *
 * 响应 JSON 数据
 *      code        状态码。0 表示成功，1 表示失败，2 表示权限错误。
 *      msg         操作出错原因。
 *      count       未分页时，满足条件的数据总量。
 *      data        学生信息列表。类型为数组，数组元素类型为对象：
 *                  {id: number, card: string, name: string, gender: boolean, birth: string, email: string, remark: string}
 *
 * 备注
 *      要求 session.login 必须是 Admin 且非空。
 *
 * @author hucsmn
 */
@WebServlet("/api/student/list")
public class StudentListServlet extends HttpServlet {
    private final StudentService studentService = StudentService.getInstance();
    private final Gson gson = new GsonBuilder().serializeNulls().create();

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=UTF-8");

        int page = ConvertUtils.parseId(request.getParameter("page")).orElse(1);
        int limit = ConvertUtils.parseId(request.getParameter("limit")).orElse(10);
        String contains = ConvertUtils.normalizeText(request.getParameter("contains"));

        JsonObject result = new JsonObject();
        HttpSession session = request.getSession();
        if (!(session.getAttribute("login") instanceof Admin)) {
            result.addProperty("code", 2);
            result.addProperty("msg", "没有权限");
        } else {
            long count = studentService.count(contains);
            List<Student> list = studentService.list(contains, page, limit);
            if (list != null) {
                result.addProperty("code", 0);
                result.addProperty("msg", "");
                result.addProperty("count", count);
                result.add("data", gson.toJsonTree(list));
            } else {
                result.addProperty("code", 1);
                result.addProperty("msg", "查询学生信息失败");
            }
        }

        PrintWriter out = response.getWriter();
        out.write(gson.toJson(result));
        out.flush();
        out.close();
    }
}
